package com.dd.front.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(getAllowCredentials())
                .allowedOriginPatterns(getAllowedOrigins())
                .allowedMethods(getAllowedMethods())
                .allowedHeaders(getAllowedHeaders())
                .exposedHeaders(getExposedHeaders())
                .maxAge(getMaxAge());
    }

    @Value("${cors.allowed-origins:*}")
    private String[] allowedOrigins;

    @Value("${cors.allowed-methods:GET,POST,PUT,DELETE,OPTIONS,HEAD,PATCH,CONNECT}")
    private String[] allowedMethods;

    @Value("${cors.allowed-headers:*}")
    private String[] allowedHeaders;

    @Value("${cors.exposed-headers:}")
    private String[] exposedHeaders;

    @Value("${cors.allow-credentials:true}")
    private boolean allowCredentials;

    @Value("${cors.max-age:3600}")
    private long maxAge;

    private String[] getAllowedOrigins() {
        return allowedOrigins;
    }

    private String[] getAllowedMethods() {
        return allowedMethods;
    }

    private String[] getAllowedHeaders() {
        return allowedHeaders;
    }

    private String[] getExposedHeaders() {
        // 如果没有配置暴露头，则默认暴露Authorization
        if (exposedHeaders.length == 0) {
            return new String[]{"Authorization"};
        }
        return exposedHeaders;
    }

    private boolean getAllowCredentials() {
        return allowCredentials;
    }

    private long getMaxAge() {
        return maxAge;
    }
}
